<!--
 * @Author: 噜噜雯雯 2199987619@qq.com
 * @Date: 2025-06-21 16:36:53
 * @LastEditors: 噜噜雯雯 2199987619@qq.com
 * @LastEditTime: 2025-09-28 11:10:19
 * @FilePath: \linePatrol\vue-element-plus-admin\src\views\EquipManage\EquipType\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, reactive, h } from 'vue'
import { ElTag } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useDictStore } from '@/store/modules/dictData'
import { BaseButton } from '@/components/Button'
import { Dialog } from '@/components/Dialog'
import { ProducerLedger } from '@/api/securcheck/type'
import Write from './components/write.vue'
import { Search } from '@/components/Search'
import SecurCheckProducerLedgerApi from '@/api/securcheck/ProducerLedger'
import { useSecurCheckStore } from '@/store/modules/securcheck'
const { t } = useI18n()
const ids = ref<string[]>([])
const DictStore = useDictStore()
//获取字典
DictStore.setDict('producer_type') //厂商类型
DictStore.setDict('producer_rating') //评级
const SecurCheckStore = useSecurCheckStore()
//表格内容接口
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const i = await SecurCheckProducerLedgerApi.GetProducerLedger({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: i.rows,
      total: i.total
    }
  },
  fetchDelApi: async () => {
    const res = await SecurCheckProducerLedgerApi.DeletProducerLedger(unref(ids)[0])
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const FormDisabled = ref(true)
//表格结构
const trackFile: any = ref([])
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    type: 'selection',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    fixed: 'left',
    search: { hidden: true }
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    fixed: 'left',
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },

  {
    field: 'producerName',
    label: t('厂商名称'),
    width: 120,
    search: {
      hidden: false,
      component: 'Input',
      componentProps: {
        placeholder: '厂商名称'
      }
    }
  },
  {
    field: 'state',
    label: t('状态'),
    search: {
      hidden: false,
      component: 'RadioButton',
      value: '',
      componentProps: {
        options: [
          {
            label: '全部',
            value: ''
          },
          {
            label: '启用',
            value: 0
          },
          {
            label: '禁用',
            value: 1
          }
        ]
      }
    },
    formatter: (_: Recordable, __: any, cellValue: number) => {
      return h(
        ElTag,
        {
          type: cellValue == 0 ? 'success' : 'danger'
        },
        () => (cellValue == 0 ? t('启用') : t('禁用'))
      )
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '启用',
            value: 0
          },
          {
            label: '禁用',
            value: 1
          }
        ]
      }
    }
  },
  {
    field: 'type',
    label: t('厂商类型'),
    search: { hidden: true },
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.producer_type?.map((item) => {
        if (item.dictValue == cellValue) {
          return t(item.dictLabel)
        }
      })
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.producer_type?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'rating',
    label: t('评级'),
    search: { hidden: true },
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.producer_rating?.map((item) => {
        if (item.dictValue == cellValue) {
          return t(item.dictLabel)
        }
      })
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.producer_rating?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'producerIntro',
    label: t('厂商简介'),
    search: { hidden: true },
    form: {
      colProps: {
        span: 24
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'userOne',
    label: t('联系人1'),
    search: { hidden: true }
  },
  {
    field: 'phoneOne',
    label: t('联系电话1'),
    search: { hidden: true }
  },
  {
    field: 'userTwo',
    label: t('联系人2'),
    search: { hidden: true }
  },
  {
    field: 'phoneTwo',
    label: t('联系电话2'),
    search: { hidden: true }
  },
  {
    field: 'address',
    label: t('地址'),
    search: { hidden: true },
    form: {
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 200,
    fixed: 'right',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <span class="TableBtn" onClick={() => action(data.row, 'Edit')}>
                {t('修改')}
              </span>
              <span class="TableBtn" onClick={() => action(data.row, 'Detail')}>
                {t('查看')}
              </span>

              <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                {t('删除')}
              </span>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const currentRow = ref<ProducerLedger>()
const saveLoading = ref(false)
const delLoading = ref(false)
//表格删除操作
const delData = async (row: ProducerLedger | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.uuid] : elTableExpose?.getSelectionRows().map((v: any) => v.uuid) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
    SecurCheckStore.setAllProducerLedger() //修改整体厂商
  })
}
const dialogVisible = ref(false)
const dialogTitle = ref('')
const MeterLedgerRef = ref()
const actionType = ref('')

const save = async () => {
  const write = unref(MeterLedgerRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    saveLoading.value = false
    const res: any = ref(false)
    //新增任务组
    if (actionType.value == 'add') {
      res.value = await SecurCheckProducerLedgerApi.AddProducerLedger(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else if (actionType.value == 'Edit') {
      //修改字
      res.value = await SecurCheckProducerLedgerApi.EditProducerLedger(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
      SecurCheckStore.setAllProducerLedger() //修改整体厂商
    }
  }
}
//表格中操作
const action = async (row: ProducerLedger, type: string) => {
  trackFile.value = []
  actionType.value = type
  dialogVisible.value = true //打开弹窗
  if (type == 'add') {
    dialogTitle.value = '新增'
    FormDisabled.value = false
    currentRow.value = {}
  } else if (type == 'Edit') {
    const res = await SecurCheckProducerLedgerApi.GetProducerLedgerById(row.uuid)
    dialogTitle.value = '修改'
    FormDisabled.value = false
    currentRow.value = res
  } else {
    const res = await SecurCheckProducerLedgerApi.GetProducerLedgerById(row.uuid)
    dialogTitle.value = '查看'
    FormDisabled.value = true
    currentRow.value = res
  }
}
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
</script>
<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px" title="厂商台账">
      <BaseButton size="small" type="primary" @click="action({}, 'add')" class="AddbtnStyle">
        <Icon icon="ep:plus" :size="13" />新增
      </BaseButton>
      <Search
        :schema="allSchemas.searchSchema"
        @search="setSearchParams"
        @reset="setSearchParams"
      />
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        row-key="uuid"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>
    <Dialog v-model="dialogVisible" :title="dialogTitle" style="width: 800px">
      <Write
        ref="MeterLedgerRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
        :FormDisabled="FormDisabled"
      />
      <template #footer>
        <BaseButton type="primary" :loading="saveLoading" @click="save">
          {{ t('提交') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('关闭') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
<style scoped>
:deep(.el-radio-button--small .el-radio-button__inner) {
  padding: 7px 15px !important;
}
.el-tree-node:focus > .el-tree-node__content {
  color: #409eff;
}
.el-card__body {
  padding: 10px;
  /* height: 90%; */
}
.CloseBtn {
  font-weight: 600;
  margin: 0 3px;
  color: darkgrey;
}
.AddbtnStyle {
  margin-bottom: 18px;
  margin-right: 10px;
}
.el-collapse-item {
  padding: 15px 0;
}
.el-collapse-item__content {
  padding-bottom: 0;
}
.el-collapse-item__header {
  width: 62px;
  height: 24px;
  border-radius: 2px;
  color: white;
  background: #409eff;
  justify-content: center;
  font-size: 12px;
}
.el-collapse-item__arrow {
  margin: 0 2px;
}

:deep(.TableBtn) {
  margin: 0 5px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600;
}
</style>
